<template>
  <div>
    <el-upload action="#" v-model:file-list="fileList" ref="uploadRef" class="upload" :limit="props.limit"
      :multiple="true" :show-file-list="true" :disabled="loading" :http-request="handleHttpUpload"
      :before-remove="handleRemove" :accept="parameter.fileType.join(',')">
      <slot name="empty">
        <el-button text :loading="loading"><svg-icon class="mr-1" icon-class="add1" /> 上传附件</el-button>
      </slot>
      <template #tip>
        <slot name="tip">
        </slot>
      </template>
    </el-upload>
  </div>
</template>
<script setup name="FileUpload">
import { reactive, toRefs } from 'vue'
import { uploadFile } from '@/api/index.js'
import { ElMessage } from 'element-plus'
const data = reactive({
  uploadRef: null,
  visible: false,
  loading: false,
  binary: null,
  parameter: {
    title: '',
    fileSize: 10,
    fileType: []
  }
})

const { visible, loading, parameter, uploadRef } = toRefs(data)

const props = defineProps({
  limit: {
    type: Number,
    default: 0,
  },
  files: {
    type: Array,
    default: [],
  },
});

const fileList = computed({
  get() {
    return props.files
  },
  set(val) {
    emits('update:files', val)
  }
})


// 获取 el-form 组件上下文
// 接收父组件参数
const acceptParams = (params) => {
  parameter.value = { ...parameter.value, ...params }
  visible.value = true
}

const handleRemove = (file, fileList) => {
  emits('update:files', fileList.value)
}
/**
 * @description 图片上传
 * @param options upload 所有配置项
 * */
const emits = defineEmits(['update:files'])
const handleHttpUpload = async (options) => {
  loading.value = true
  let formData = new FormData()
  const { file } = options
  formData.append('file', file)
  uploadFile(formData)
    .then((res) => {
      ElMessage.success(res.message)
      fileList.value.push({
        name: res.data['filename'],
        url: res.data['data-show-file'],
      })
    })
    .finally(() => {
      loading.value = false
    })
}
defineExpose({
  acceptParams
})
</script>
<style lang="scss" scoped>
:deep(.el-upload-list) {
  display: flex;
  justify-content: flex-start;

  .el-upload-list__item {
    margin-right: 40px;
  }
}
</style>
